package com.spring.security;

import com.spring.security.authentication.HkAuthenticationFailureHandler;
import com.spring.security.authentication.HkAuthenticationSuccessHandler;
import com.spring.security.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.spring.security.properties.SecurityConstants;
import com.spring.security.social.openid.OpenIdAuthenticationSecurityConfig;
import com.spring.security.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.social.security.SpringSocialConfigurer;

/**
 * 资源服务器
 */
@Configuration
@EnableResourceServer
public class HkResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private HkAuthenticationSuccessHandler hkAuthenticationSuccessHandler;
    @Autowired
    private HkAuthenticationFailureHandler hkAuthenticationFailureHandler;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Autowired
    private SpringSocialConfigurer hkSocialSecurityConfig;

    @Autowired
    private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 表单登录
        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)// 处理表单登录 URL
                .successHandler(hkAuthenticationSuccessHandler)// 处理登录成功
                .failureHandler(hkAuthenticationFailureHandler);// 处理登录失败
        //配置
        http.apply(validateCodeSecurityConfig)
                .and()
                //加入短信验证码认证流程
                .apply(smsCodeAuthenticationSecurityConfig)
                .and()
                //加入社交登录
                .apply(hkSocialSecurityConfig)
                .and()
                //通过providerId=qq  weixin和openId登录
                .apply(openIdAuthenticationSecurityConfig)
                .and()
                .authorizeRequests() // 授权配置
                //不需要认证的路径
                .antMatchers(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*",
                        SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
                        SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL,
                        "/user/regist").permitAll()
                .anyRequest() // 所有请求
                .authenticated() // 都需要认证
                .and().csrf().disable();
    }
}
